/*
题目链接:https://leetcode.cn/problems/closest-equal-element-queries/description/
*/

//题解代码:
class Solution {
public:
    vector<int> solveQueries(vector<int>& nums, vector<int>& que) {
        unordered_map<int,vector<int>> ump;
        int n = nums.size(),m = que.size();
        for(int i=0;i<n;++i) nums.push_back(nums[i]);
        for(int i=0;i<2*n;++i){
            ump[nums[i]].push_back(i);
        }

        vector<int> ans(m,INT_MAX);
        for(int i=0;i<m;++i){
            int qi= que[i];
            auto& idx = ump[nums[qi]];
            int j1 = lower_bound(idx.begin(),idx.end(),qi) - idx.begin();
            int j2 = lower_bound(idx.begin(),idx.end(),qi+n) - idx.begin();
            ans[i] = min(idx[j1+1]-idx[j1],idx[j2]-idx[j2-1]);
            if(ans[i]==n) ans[i] = -1;
        }
        return ans;
    }
};
